import { diskStorage } from 'multer';
import * as path from 'path';
import * as fs from 'fs-extra';
import { FileType } from "@/common/enums/file.enum"

export const multerOptions = (fileTypes: string[]) => ({
  storage: diskStorage({
    destination: async (req, file, callback) => {
      const dest = path.join(process.cwd(), 'storage', 'temp');
      await fs.ensureDir(dest); // 确保目录存在
      callback(null, dest);
    },
    filename(req, file, callback) {
      const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
      callback(null, `${uniqueSuffix}-${file.originalname}`);
    }
  }),
  limits: {
    fileSize: 1024 * 1024 * 100, // 文件大小100M
    files: 5,// 同时上传文件数量5
  },
  fileFilter: (req, file, cb) => {
    // 允许的文件类型
    const allowedTypes = fileTypes || [
      'text/plain',        // .txt
      'application/pdf',   // .pdf
      'image/jpeg',        // .jpg
      'image/png',         // .png
      'application/zip',   // .zip
      'application/json',  // .json
    ];

    if (allowedTypes.includes(file.mimetype)) {
      cb(null, true);
    } else {
      cb(new Error('不支持的文件类型'), false);
    }
  },
})


const dirs = [
  path.join(process.cwd(), 'storage', 'temp'),
  path.join(process.cwd(), 'storage', 'files', FileType.Novel),
  path.join(process.cwd(), 'storage', 'files', FileType.Document),
  path.join(process.cwd(), 'storage', 'files', FileType.Image),
  path.join(process.cwd(), 'storage', 'files', FileType.Other),
];

for (const dir of dirs) {
  fs.ensureDir(dir);
  console.log(`✅ 目录已创建: ${dir}`);
}